import 'package:common_utils/common_utils.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';

import 'state.dart';

class AftersaleApplyLogic extends GetxController {
  final state = AftersaleApplyState();
  var all_refund = 0;

  void onReady() {
    super.onReady();
    //type 1是多个商品 0是1个商品
    var type = Get.arguments['type'];
    state.id = Get.arguments['id'];
    state.data = Get.arguments['data'];
    state.isPre = Get.arguments['isPre'];
    LogUtil.d("==state.data:${state.data}");
    if(state.isPre != 1){
      state.num = state.data['remain_cancel_qty'].toInt();
      state.maxnum = state.data['remain_cancel_qty'].toInt();
    }
    if (type == 1) {
      state.datelis.addAll(state.data);
    } else {
      state.datelis.add(state.data);
      state.num = state.datelis[0]["remain_cancel_qty"].toInt();
      LogUtil.d("state.num===============state.num:：${state.num}");
    }
    LogUtil.d("商品列表：${state.datelis}");

    /// 获取订单详情
    var params = {
      'tml_num_id': state.id,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'user_type': 1,
    };

    Api.orderDetail(params).listen((event) {
      LogUtil.d("获取订单详情=======$event");
      state.detail = event['distribution_order_detail'];
      for (var item in event['distribution_order_detail']["distribution_order_item"]) {
        if (item['pmt_sign'] == 1 && item['remain_cancel_qty'] > 0) {
          // all_refund = 1;
          state.datelis.add(item);
        }
      }
      for (int i = 0; i < state.datelis.length; i++) {
        int _num = state.datelis[i]['remain_cancel_qty'].toInt();
        int _maxNum = state.datelis[i]['remain_cancel_qty'].toInt();
        state.datelis[i]['max_num'] = _maxNum;
        state.datelis[i]["num"] = _num;
      }
      update();
    });

    /// 退款原因
    var params1 = {
      'table_name': 'common',
      'field_name': 'return_type',
      'updatedata': 2,
    };
    Api.cType(params1).listen((event) {
      // LogUtil.d("退款原因=========$event");
      List list = event['types'];
      list.forEach((element) {
        element['selected'] = false;
      });
      state.classList = list;
      update();
    });
    update();
  }

  void setType(int index) {
    state.type = index;
    update();
  }

  void select(int i) {
    List list = state.classList;
    list.forEach((element) {
      element['selected'] = false;
    });
    state.classList[i]['selected'] = true;
    update();
  }

  // 减
  // void reduce(int index) {
  //   LogUtil.d("减:${state.datelis[index]["num"].toString()}");
  //   if (state.datelis[index]["num"] == state.minnum) {
  //     toast('最低不能少于1件');
  //     return;
  //   }
  //   // state.num--;
  //   state.datelis[index]["num"]--;
  //   update();
  // }
  //
  // // 加
  // void add(int index) {
  //   LogUtil.d("加:${state.datelis[index]["num"].toString()}");
  //   if (state.datelis[index]["num"] == state.datelis[index]["max_num"]) {
  //     toast('不能大于最大申请数量');
  //     return;
  //   }
  //   // state.num++;
  //   state.datelis[index]["num"]++;
  //   update();
  // }

  // // 减
  void reduce(int index) {
    if (state.isPre == 1) {
      if (state.datelis[0]["num"] == state.minnum) {
        toast('最低不能少于1件');
        return;
      }
      state.datelis[0]["num"]--;
      LogUtil.d("商品数量：${state.datelis[0]["num"]}   state.isPre:${state.isPre}");
    } else {
      if (state.num == state.minnum) {
        toast('最低不能少于1件');
        return;
      }
      state.num--;
      LogUtil.d("商品数量：${state.num}   state.isPre:${state.isPre}");
    }

    update();
  }

  // 加
  void add(int index) {
    if (state.isPre == 1) {
      if (state.datelis[0]["num"] == state.datelis[0]["max_num"]) {
        toast('不能大于最大申请数量');
        return;
      }
      state.datelis[0]["num"]++;
      LogUtil.d("商品数量：${state.num}   state.isPre:${state.isPre}");
    } else {
      if (state.num == state.maxnum) {
        toast('不能大于最大申请数量');
        return;
      }
      state.num++;
      LogUtil.d("商品数量：${state.num}   state.isPre:${state.isPre}");
    }
    update();
  }

  submit() {
    List list = state.classList;
    var data = null;
    list.forEach((element) {
      if (element['selected'] == true) {
        data = element;
      }
    });
    state.remark = data['type_name'];
    state.typeId = data['type_num_id'];
    update();
    print(data);
  }

  /// 提交申请
  void submitApply() {
    // if(state.fileList.length==0){
    //   toast('请上传图片');
    //   return;
    // }
    if (state.typeId == null) {
      toast('请选择售后原因');
      return;
    }
    if (state.controller.text.length > 400) {
      toast('问题描述不能大于400字');
      print(state.controller.text.length);
      return;
    }

    var params = null;

    // if(state.num==state.maxnum){
    //   params = {
    //     'access_token': SpUtil.getString('token'),
    //     'source_tml_num_id':state.id,
    //     'all_refund':1,
    //     'return_type':state.typeId,
    //     'remark'	:state.controller.text,
    //     'evidence_list':state.fileList,
    //     'return_way':state.type
    //   };
    // }else{
    var items = [];
    for (var item in state.datelis) {
      var qty;
      if (state.isPre == 1) {
        qty = item['pmt_sign'] == 1 ? item['remain_cancel_qty'] : item["num"];
      } else {
        qty = item['pmt_sign'] == 1 ? item['remain_cancel_qty'] : state.num;
      }
      items.add({
        "item_num_id": item['item_num_id'],
        // "qty": item['pmt_sign'] == 1 ? item['remain_cancel_qty'] : state.num,
        "qty": qty,
        "price": item['trade_price'],
        "pmt_sign": item['pmt_sign'], //是否赠品
        "trade_amount": null,
        "tml_line": item['tml_line']
      });
    }
    params = {
      'source_tml_num_id': state.id,
      'access_token': SpUtil.getString('token'),
      'items': items, //商品
      'all_refund': all_refund,
      'return_type': state.typeId,
      'remark': state.controller.text,
      'evidence_list': state.fileList,
      'return_way': state.type
    };
    // params = {
    //   'source_tml_num_id': state.id,
    //   'access_token': SpUtil.getString('token'),
    //   'items': [
    //     {
    //       "item_num_id": state.data['item_num_id'],
    //       "qty": state.num,
    //       "price": state.detail['real_pay_amount'],
    //       "pmt_sign": state.data['pmt_sign'], //是否赠品
    //       "trade_amount": null,
    //       "tml_line": state.data['tml_line']
    //     }
    //   ],
    //   'all_refund': 0,
    //   'return_type': state.typeId,
    //   'remark': state.controller.text,
    //   'evidence_list': state.fileList,
    //   'return_way': state.type
    // };

    LogUtil.d("提交参数:$params");
    Api.tkApply(params).listen((event) {
      if (event['code'] == 0) {
        toast(event['message']);
        Get.toNamed(RouteConfig.applySuccess,
            arguments: {'back_tml_num_id': event['back_tml_num_id']});
      } else {
        toast(event['message']);
      }
      update();
    });
  }
}
